package leetcode.median;

import java.util.Arrays;

public class $611_TriangleNumber {
    public int triangleNumber(int[] nums) {
        int len = nums.length;
        Arrays.sort(nums);
        int res = 0;
        for (int i = 0;i < len - 2; i++) {
            for (int j = i + 1; j < len - 1;j++) {
                for (int k = j + 1;k < len;k++) {
                    int sum = nums[i] + nums[j];
                    if (sum > nums[k])
                        res++;
                }
            }
        }
        return res;
    }

    public int triangleNumber2(int[] nums) {
        int len = nums.length;
        Arrays.sort(nums);
        int res = 0;
        for (int i = 0;i < len - 2; i++) {
            for (int j = i + 1; j < len - 1;j++) {
                int sum = nums[i] + nums[j];
                int left = j + 1;
                int right = len - 1;
                while (left <= right) {
                    int mid = left + (right - left) / 2;
                    if (nums[mid] > sum) {
                        right = mid -1;
                    } else if(nums[mid] == sum) {
                        right = mid - 1;
                    } else {
                        // 从left到mid都可以
                        left = mid + 1;
                    }
                }
                if (sum > nums[right]) {
                    res += (right - j);
                }
            }
        }
        return res;
    }
}
